#include "ip2subnetmask.h"

vector<string> ip2subnetmask::string_split (string str, string delimiters)
{
    // Outputs a vector containing the substrings seperated by delemeter.
    // Got help from http://www.linuxselfhelp.com/HOWTO/C++Programming-HOWTO-7.html
    vector<string> tokens;
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
    return tokens;
}

int ip2subnetmask::log2(int a)
{
    return ceil(log10(a)/log10(2));
}

string ip2subnetmask::int2string(int i){
    stringstream out;
    out << i;
    return out.str();
}

string ip2subnetmask::ip2snm(string ip){
    vector<string> ipOctets = string_split(ip, ".");
    string result = "";
    if(ipOctets.size() != 4){
        result = "error";
        return result;
    }
    int ipa = atoi(ipOctets[0].c_str());
    int ipb = atoi(ipOctets[1].c_str());
    int ipc = atoi(ipOctets[2].c_str());
    int ipd = atoi(ipOctets[3].c_str());
    int sma=0,smb=0,smc=0,smd=0;
    if(1<=ipa && ipa <=126) sma=255;
    else if(128<=ipa && ipa <=191) sma=255,smb=255;
    else if(192<=ipa && ipa <=223) sma=255,smb=255,smc=255;

    int t = 8-log2(log2(ipb) + 2);
    unsigned char c=0xFF;
    while(t--)
    {
        c = c << 1;
        c &= 0xFE;
    }
    // convert ints to string
    result = int2string(sma) + "." + int2string(smb) + "." + int2string(smc) + "." + int2string(smd);
    return result;
}
